#include "database_handler/media_control.hh"
#include <cgicc/Cgicc.h>
#include <cgicc/HTMLClasses.h>
#include <cgicc/HTTPPlainHeader.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

using namespace cgicc;
using namespace std;
using namespace leyi_media;
void response_error(const string &content)
{
    html out_doc(head(meta().set("charset", "UTF8")).add(title("上传失败")));
    out_doc.add(h1("错误原因: " + content))
        .add(h2("遇到问题 请联系: ").add(a("leyi_999@outlook.com")));
    exit(EXIT_FAILURE);
}
// 连接数据库
// 获取视频
// 存视频
// cmd ffmpeg获取缩略图
// 拿到数据
// 拿到信息
// 添加到数据库
const string base_dir = "wwwroot/ktv/";
const string video_dir = "videos/";
const string thumb_dir = "img/thumbs/";
int main()
{
    cout << "Content-Type: plain/text"
         << "\r\n\r\n";
    try
    {
        Cgicc cc;
        cout << HTTPPlainHeader();
        // 拿文件
        auto files = cc.getFiles();
        auto video_file = cc.getFile("video-file");
        if (video_file == cc.getFiles().end())
        {
            std::cout << "cant get file";
            return 1;
        }
        // 存文件
        string video_file_name = video_file->getFilename();
        string thumb_file_name = video_file->getFilename() + ".jpg";
        std::filesystem::path video_path = base_dir + video_dir + video_file_name;
        std::filesystem::path thumb_path = base_dir + thumb_dir + thumb_file_name;
        std::ofstream ofs(video_path, std::ios::trunc | std::ios::out);
        video_file->writeToStream(ofs);
        // 转码
        string converted_video_file_name = video_path.stem().string() + ".mp4";
        string converted_video_path = base_dir + video_dir + converted_video_file_name;
        std::string convert_option = " -loglevel quiet -c:v libx264 -preset medium -b:v 900k -c:a aac -strict experimental -movflags +faststart ";
        std::string convert_cmd = "ffmpeg -i " + video_path.string() + convert_option + converted_video_path;
        system(convert_cmd.data());
        // 缩略图
        std::string thumbnail_cmd = "ffmpegthumbnailer -i " + converted_video_path + " -o " + thumb_path.string() + " -s 320 ";
        system(thumbnail_cmd.data());
        // 存数据
        media_control::media_controler_t &mysql_instance = media_control::media_controler_t::get_instance();
        Json::Value root;
        root["name"] = cc.getElement("video-name")->getValue();
        root["info"] = cc.getElement("video-info")->getValue();
        root["duration"] = cc.getElement("video-duration")->getValue();
        root["video_path"] = video_dir+converted_video_file_name;
        root["thumb_path"] = thumb_dir+thumb_file_name;
        if (mysql_instance.insert_video(root))
            cout << "upload success";
        else
            cout << "error";
    }
    catch (const std::exception &e)
    {
        std::cerr << "throwed: ";
        std::cerr << e.what() << std::endl;
    }
    return 0;
}